﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Serialization;
using System.Collections.ObjectModel;
using System.Data.SqlTypes;
using System.Text;
using System.Web.Security;
using HotelApp;

namespace HotelWeb
{
    /// <summary>
    /// Summary description for HotelWebService
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class HotelWebService : System.Web.Services.WebService
    {
        #region AdminInfo

        [WebMethod]
        public void CreateAdminInfo()
        {
            AdminInfo info = GetAdminInfoUI();
            try
            {
                HotelAppOM.CreateAdminInfo(info, Context.User.Identity.Name);
                ExecuteResult(true, "success");
            }
            catch (Exception ex)
            {
                ExecuteResult(false, ex.Message);
            }
        }

        [WebMethod]
        public void UpdateAdminInfo()
        {
            AdminInfo info = GetAdminInfoUI();
            try
            {
                HotelAppOM.UpdateAdminInfo(info, Context.User.Identity.Name);
                ExecuteResult(true, "success");
            }
            catch (Exception ex)
            {
                ExecuteResult(false, ex.Message);
            }
        }

        [WebMethod]
        public void DeleteAdminInfo(string userCode)
        {
            try
            {
                HotelAppOM.DeleteAdminInfo(userCode, Context.User.Identity.Name);
                ExecuteResult(true, "success");
            }
            catch (Exception ex)
            {
                ExecuteResult(false, ex.Message);
            }
        }

        [WebMethod]
        public void ListAdminInfos()
        {
            List<AdminInfo> lst = AdminInfoDAO.ListAdminInfos().ToList();
            JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
            jsSerializer.RegisterConverters(new List<JavaScriptConverter>(new JavaScriptConverter[] { new SqlDateTimeConverter() }));
            Context.Response.ContentType = "application/json";
            Context.Response.Write(jsSerializer.Serialize(lst));
        }


        [WebMethod]
        public void LoginSystem(string userName, string password)
        {
            try
            {
                HotelAppOM.LoginSystem(userName, password);
                FormsAuthentication.SignOut();
                FormsAuthentication.SetAuthCookie(userName, true);
                ExecuteResult(true, "Success");
            }
            catch (Exception ex)
            {
                ExecuteResult(false, ex.Message);
            }
        }

        [WebMethod]
        public void LoginOff()
        {
            FormsAuthentication.SignOut();
            ExecuteResult(true, "success");
        }

        [WebMethod]
        public void ValidLoginUser()
        {

            if (User.Identity.IsAuthenticated)
            {
                ExecuteResult(true, Context.User.Identity.Name);
            }
            else
            {
                ExecuteResult(false, "Login failed");
            }
        }

        #endregion

        #region NewsCategory

        [WebMethod]
        public void CreateNewsCategory()
        {
            NewsCategory obj = GetNewsCategoryFormUI();
            try
            {
                HotelAppOM.CreateNewsCategory(obj, Context.User.Identity.Name);
                ExecuteResult(true, "success");
            }
            catch (Exception ex)
            {
                ExecuteResult(false, ex.Message);
            }
        }

        [WebMethod]
        public void UpdateNewsCategory()
        {
            NewsCategory obj = GetNewsCategoryFormUI();
            try
            {
                HotelAppOM.UpdateNewsCategory(obj, Context.User.Identity.Name);
                ExecuteResult(true, "success");
            }
            catch (Exception ex)
            {
                ExecuteResult(false, ex.Message);
            }
        }

        [WebMethod]
        public void DeleteNewsCategory(string categoryCode)
        {
            try
            {
                HotelAppOM.DeleteNewsCategory(categoryCode, Context.User.Identity.Name);
                ExecuteResult(true, "success");
            }
            catch (Exception ex)
            {
                ExecuteResult(false, ex.Message);
            }
        }

        [WebMethod]
        public void ListNewsCategory()
        {
            List<NewsCategory> lst = NewsCategoryDAO.ListCategories().ToList();
            JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
            jsSerializer.RegisterConverters(new List<JavaScriptConverter>(new JavaScriptConverter[] { new SqlDateTimeConverter() }));
            Context.Response.ContentType = "application/json";
            Context.Response.Write(jsSerializer.Serialize(lst));
        }

        #endregion

        #region NewsInfo

        [WebMethod]
        public void CreateNewsInfo()
        {
            NewsInfo obj = GetNewsInfoFormUI();
            try
            {
                HotelAppOM.CreateNewsInfo(obj, Context.User.Identity.Name);
                ExecuteResult(true, "success");
            }
            catch (Exception ex)
            {
                ExecuteResult(false, ex.Message);
            }
        }

        [WebMethod]
        public void UpdateNewsInfo()
        {
            NewsInfo obj = GetNewsInfoFormUI();
            try
            {
                HotelAppOM.UpdateNewsInfo(obj, Context.User.Identity.Name);
                ExecuteResult(true, "success");
            }
            catch (Exception ex)
            {
                ExecuteResult(false, ex.Message);
            }
        }

        [WebMethod]
        public void DeleteNewsInfo(string newsCode)
        {
            try
            {
                HotelAppOM.DeleteNewsInfo(newsCode, Context.User.Identity.Name);
                ExecuteResult(true, "success");
            }
            catch (Exception ex)
            {
                ExecuteResult(false, ex.Message);
            }
        }

        [WebMethod]
        public void GetNewsInfo(string newsCode)
        {
            List<NewsInfo> lst = new List<NewsInfo>();
            NewsInfo obj = NewsInfoDAO.GetNewsInfo(newsCode);
            lst.Add(obj);
            ResponseWrite<NewsInfo>(lst);
        }

        [WebMethod]
        public void ListNewsInfo(string categoryCode, int startIndex, int limit)
        {
            int totalCount = 0;
            List<NewsInfo> lst = NewsInfoDAO.ListNewsInfos(categoryCode, startIndex, limit, ref totalCount).ToList();
            JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
            jsSerializer.RegisterConverters(new List<JavaScriptConverter>(new JavaScriptConverter[] { new SqlDateTimeConverter() }));
            Context.Response.ContentType = "application/json";
            string strJson = jsSerializer.Serialize(lst);
            strJson = "{total:" + totalCount + ",data:" + strJson + "}";
            Context.Response.Write(strJson);
        }

        #endregion

        #region private methods

        private void ResponseWrite<T>(List<T> lst)
        {
            JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
            jsSerializer.RegisterConverters(new List<JavaScriptConverter>(new JavaScriptConverter[] { new SqlDateTimeConverter() }));
            Context.Response.ContentType = "application/json";
            Context.Response.Write(jsSerializer.Serialize(lst));
        }

        private void ResponseWrite(string strJson)
        {
            Context.Response.ContentType = "application/json";
            Context.Response.Write(strJson);
        }

        private void ExecuteResult(bool isSuccess, string message)
        {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.Append("{");
            if (isSuccess)
            {
                stringBuilder.AppendFormat("success:true,");
            }
            else
            {
                stringBuilder.AppendFormat("success:false,");
            }
            stringBuilder.Append("errors:{");
            stringBuilder.AppendFormat("clientCode:'{0}'", message);
            stringBuilder.Append("}}");
            this.Context.Response.Write(stringBuilder.ToString());
        }

        private AdminInfo GetAdminInfoUI()
        {
            AdminInfo info = new AdminInfo();
            info.UserCode = this.Context.Request.Form.Get("UserCode");
            info.UserName = this.Context.Request.Form.Get("UserName");
            info.Password = this.Context.Request.Form.Get("Password");
            info.Phone = this.Context.Request.Form.Get("Phone");
            info.Email = this.Context.Request.Form.Get("Email");

            return info;
        }

        private NewsCategory GetNewsCategoryFormUI()
        {
            NewsCategory obj = new NewsCategory();
            obj.CategoryCode = this.Context.Request.Form.Get("CategoryCode");
            obj.CategoryName = this.Context.Request.Form.Get("CategoryName");
            obj.CategoryDesc = this.Context.Request.Form.Get("CategoryDesc");

            return obj;
        }

        private NewsInfo GetNewsInfoFormUI()
        {
            NewsInfo obj = new NewsInfo();
            obj.NewsCode = this.Context.Request.Form.Get("NewsCode");
            obj.CategoryCode = this.Context.Request.Form.Get("CategoryCode");
            obj.NewsName = this.Context.Request.Form.Get("NewsName");
            obj.NewsDesc = this.Context.Request.Form.Get("NewsDesc");
            obj.NewsContent = this.Context.Request.Form.Get("NewsContent");
            obj.Creator = this.Context.User.Identity.Name;

            return obj;
        }

        private string ConvertStringToJson(HttpRequest request)
        {

            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < request.Form.Keys.Count; i++)
            {
                sb.Append(request.Form.Keys[i] + ":" + request.Form.Get(request.Form.Keys[i]) + ",");
            }

            return "{" + sb.ToString().Substring(0, sb.Length - 1) + "}";
        }

        #endregion
    }
}

public class SqlDateTimeConverter : JavaScriptConverter
{
    public override IEnumerable<Type> SupportedTypes
    {
        get { return new ReadOnlyCollection<Type>(new List<Type>(new Type[] { typeof(SqlDateTime) })); }
    }

    public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
    {
        SqlDateTime objSqlDateTime = (SqlDateTime)obj;

        if (!objSqlDateTime.IsNull)
        {
            Dictionary<string, object> listDict = new Dictionary<string, object>();
            listDict.Add("val", objSqlDateTime.Value.ToString("MM/dd/yyyy"));

            return listDict;
        }
        return new Dictionary<string, object>();
    }

    public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
    {
        return null;
    }
}
